package com.ruoyi.project.sdi.scan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.BillType;
import com.ruoyi.common.enums.WorkloadType;
import com.ruoyi.common.utils.CommonParaTool;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.bms.bmsVoucherAssociate.domain.BmsVoucherAssociate;
import com.ruoyi.project.bms.bmsVoucherAssociate.service.IBmsVoucherAssociateService;
import com.ruoyi.project.param.paeaParaSystem.domain.PaeaParaSystem;
import com.ruoyi.project.param.paeaParaSystem.enums.ArchiveServerType;
import com.ruoyi.project.param.paeaParaSystem.service.IPaeaParaSystemService;
import com.ruoyi.project.sdi.scan.model.ScanSubmitReq;
import com.ruoyi.project.sdi.scan.service.IScanService;
import com.ruoyi.project.sdi.sdiImage.domain.SdiImage;
import com.ruoyi.project.sdi.sdiImage.service.ISdiImageService;
import com.ruoyi.project.sdi.sdiPaeaArc.domain.SdiPaeaArc;
import com.ruoyi.project.sdi.sdiPaeaArc.model.SdiPaeaArcScanRequest;
import com.ruoyi.project.sdi.sdiPaeaArc.model.SdiPaeaArcScanResponse;
import com.ruoyi.project.sdi.sdiPaeaArc.service.ISdiPaeaArcService;
import com.ruoyi.project.stat.paeaReportWorkload.domain.PaeaReportWorkload;
import com.ruoyi.project.stat.paeaReportWorkload.service.IStatisticsWorkloadService;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.tool.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * 功能描述：
 *
 * @author 关晓强
 * @version 1.0
 * @date 2020/3/17 10:46
 */
@Controller
@Slf4j
@RequestMapping("/sdi/scan")
public class ScanController extends BaseController {

    private String prefix = "sdi/scan";

    @Autowired
    private IPaeaParaSystemService paeaParaSystemService;

    @Autowired
    private ISdiPaeaArcService sdiPaeaArcService;

    @Autowired
    private ISdiImageService sdiImageService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IScanService scanService;

    @Autowired
    private IBmsVoucherAssociateService bmsVoucherAssociateService;

    @Autowired
    private IStatisticsWorkloadService statisticsWorkloadService;


    @RequiresPermissions("sdi:scan:view")
    @GetMapping()
    public String scanWelcome()
    {
        return prefix + "/scanWelcome";
    }

    @GetMapping("/scan/{type}")
    public String scan(@PathVariable("type")String type, ModelMap mmap)
    {
        User user = ShiroUtils.getSysUser();
        PaeaParaSystem paeaParaSystem = CommonParaTool.getPaeaParaSystemByOrgCode(user.getDeptId(), ArchiveServerType.扫描专用.getCode());
        if(type.equals("normal")){
            //正常扫描
            mmap.put("g_submitUrl","/submitScan");
            mmap.put("g_chooseBatchDialogUrl","/scanBatchInfo");
            mmap.put("g_chooseBatchDialogOpt","dialogWidth=350px; dialogHeight=400px; help=no; toolbar=no;status=no; scroll=no; resizable=no");
        } else if(type.equals("add")){
            //补扫
            mmap.put("g_submitUrl","/submitScanAdd");
            mmap.put("g_chooseBatchDialogUrl","/scanAddBatchInfo");
            mmap.put("g_chooseBatchDialogOpt","dialogWidth=900px; dialogHeight=600px; help=no; toolbar=no;status=no; scroll=no; resizable=no");
        } else if(type.equals("other")){
            //其他扫描
            mmap.put("g_submitUrl","/submitScan");
            mmap.put("g_chooseBatchDialogUrl","/scanBatchInfo");
            mmap.put("g_chooseBatchDialogOpt","dialogWidth=900px; dialogHeight=600px; help=no; toolbar=no;status=no; scroll=no; resizable=no");
        }

        mmap.put("paeaParaSystem",paeaParaSystem);
        mmap.put("asynFlag","0");
        return prefix + "/scan";
    }

    @GetMapping("/scanBatchInfo")
    public String scanBatchInfo()
    {
        return prefix + "/scanBatchInfo";
    }

    @GetMapping("/scanAddBatchInfo")
    public String scanAddBatchInfo()
    {
        return prefix + "/scanAddBatchInfo";
    }

    /**
     * 检查批次是否可扫描
     * @param sdiPaeaArcScanRequest
     * @param mmap
     * @return
     */
    @PostMapping("/checkBatchScannable")
    @ResponseBody
    public AjaxResult checkBatchScannable(SdiPaeaArcScanRequest sdiPaeaArcScanRequest, ModelMap mmap) {
        SdiPaeaArcScanResponse sdiPaeaArcScanResponse = new SdiPaeaArcScanResponse();
        User user = ShiroUtils.getSysUser();
        int scanType = sdiPaeaArcScanRequest.getScanType();
        //验证机构所属监控中心是否设置文档服务器，没有的话提示不能进行扫描
        String userDeptId = user.getDeptId();
        //todo 改为缓存中获取
        PaeaParaSystem paeaParaSystem = CommonParaTool
                .getPaeaParaSystemByOrgCode(userDeptId+"");
        if(paeaParaSystem==null){
            return AjaxResult.warn("该机构所属监控中心没有正确设置文档服务器，无法扫描");
        }
        int registerNum = 0;
        String subPath = "";
        //验证批次信息的真实性
        if (scanType == 1) {
            SdiPaeaArc sdiPaeaArc = sdiPaeaArcService.getOne(new QueryWrapper<SdiPaeaArc>()
                        .eq("tr_date",sdiPaeaArcScanRequest.getTrDate())
                        .eq("org_code",sdiPaeaArcScanRequest.getOrgCode())
                        .eq("teller_code",sdiPaeaArcScanRequest.getTellerCode()));

            if (sdiPaeaArc == null) {
                return AjaxResult.error("该批次不存在，无法直接上传影像");
            }
            List<SdiImage> sdiImages = sdiImageService.getSdiImagesBySdiPaeaArc(sdiPaeaArc);
            if (sdiImages == null) {
                return AjaxResult.error("批次下不存在影像！");
            }
            String fpath = sdiImages.get(0).getSdifilepath();
            /**
             * 文档服务器存储路径格式如下：
             *
             * @desc /2011/201105/20110509/00a0/0288/0288QF/8
             *       a8c82c92fd76486012fd7c65efd028b/00000005.JPG
             */
            String[] result = fpath.split("/");
            if (result.length != 9 || result[7].trim().length() <= 20) {
                return AjaxResult.error("文档服务器存储影像原始路径格式错误，无法上传影像！");
            }
            subPath = result[7].trim();
            sdiPaeaArcScanResponse.setRegisterNum(sdiPaeaArc.getFrontNum());
            sdiPaeaArcScanResponse.setSubPath(subPath);
            sdiPaeaArcScanResponse.setSsoOrgCode(userDeptId+"");
        } else {
            boolean b= true;
            // 从批次表检查是否扫描过
            b = scanService.isScaned(sdiPaeaArcScanRequest.getTrDate(),sdiPaeaArcScanRequest.getOrgCode(),sdiPaeaArcScanRequest.getTellerCode());
            // 从登记表检查登记信息
            BmsVoucherAssociate bmsVoucherAssociate = this.bmsVoucherAssociateService.getOne(new QueryWrapper<BmsVoucherAssociate>()
                    .eq("tr_date",sdiPaeaArcScanRequest.getTrDate())
                    .eq("org_code",sdiPaeaArcScanRequest.getOrgCode())
                    .eq("teller_code",sdiPaeaArcScanRequest.getTellerCode())
                    .eq("be",1));
            if(bmsVoucherAssociate==null) {
                return AjaxResult.error("该正常扫描批次无登记信息！");
            } else if (1!=bmsVoucherAssociate.getInceptStatus()){
                return AjaxResult.error("该批次登记信息还未接收，无法扫描！");
            } else if (0!=bmsVoucherAssociate.getScanStatus()){
                return AjaxResult.error("该批次已进行过扫描，无法重复扫描！");
            }
            registerNum = bmsVoucherAssociate.getNoteCount();
            if (!b) {
                subPath = UUID.randomUUID().toString().replaceAll("-","");
                sdiPaeaArcScanResponse.setRegisterNum(registerNum);
                sdiPaeaArcScanResponse.setSubPath(subPath);
                sdiPaeaArcScanResponse.setSsoOrgCode(userDeptId+"");
            } else {
                return AjaxResult.error("该批次已经被扫描！");
            }
        }
        return AjaxResult.success(sdiPaeaArcScanResponse);
    }


    /**
     * 校验机构号是否存在
     */
    //todo 从缓存拿机构信息
    @PostMapping("/checkOrgCodeExists")
    @ResponseBody
    public String checkOrgCodeExists(String orgCode){
        if(deptService.selectDeptById(orgCode)!=null){
            return Constants.EXISTS;
        }
        return Constants.NOT_EXISTS;
    }

    /**
     * 扫描批次提交
     */
    @PostMapping("/submitScan")
    @ResponseBody
    @Transactional
    public AjaxResult submitScan(ScanSubmitReq scanSubmitReq){
        User user = ShiroUtils.getSysUser();
        scanSubmitReq.setParentId(BillType.会计凭证.getValue());
        boolean isSubmit = scanService.submit(scanSubmitReq,user);
        // 创建差错相关
        if (!isSubmit) {
            return AjaxResult.error("该批次已做过扫描");
        }
        return AjaxResult.success("批次已经提交，可以继续扫描下一批次");
    }

    /**
     * 补扫批次提交
     */
    @PostMapping("/submitScanAdd")
    @ResponseBody
    public AjaxResult submitScanAdd(ScanSubmitReq scanSubmitReq){
        User user = ShiroUtils.getSysUser();
        String[] fileNames = scanSubmitReq.getFileNames();
        String arcId = scanSubmitReq.getArcId();
        if (fileNames == null) {
            return AjaxResult.error("文件路径不正确");
        }
        if (arcId == null || arcId.trim().length() == 0) {
            return AjaxResult.error("案卷id为空");
        }

        boolean isSubmit = this.scanService.submitAdd(scanSubmitReq,user);
        if (!isSubmit) {
            return AjaxResult.error("批次补扫提交失败");
        }
        return AjaxResult.success("批次提交成功");
    }

    /**
     * 查询当日扫描量
     */
    @GetMapping("/scanWorkload")
    @ResponseBody
    public AjaxResult scanWorkload() {
        User user = ShiroUtils.getSysUser();
        try {
            PaeaReportWorkload workLoad = statisticsWorkloadService.getOne(new QueryWrapper<PaeaReportWorkload>()
                    .eq("work_date", DateTimeUtil.getDateFormat())
                    .eq("org_code",user.getDeptId())
                    .eq("work_type",WorkloadType.扫描.getCode())
                    .eq("user_code",user.getUserId()));
            String responseText;
            if(workLoad!=null){
                responseText= "你今日已经成功提交的扫描批次数为 "
                        + workLoad.getBatchNum() + " 批, 扫描提交凭证 "
                        + workLoad.getWorkLoad() / 2 + " 张(正反面为一张)";
            } else {
                responseText= "你今日还未扫描！";
            }
            return AjaxResult.success(responseText);
        } catch (Throwable e) {
            e.printStackTrace();
            return AjaxResult.error("查询扫描量出现异常!");
        }
    }
}
